package scu.util.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import scu.util.manager.*;
import scu.util.logger.*;

public class DB {
	
	private Connection conn = null;
	private ResultSet rs = null;
	private Statement stmt = null;
	private PreparedStatement pstmt = null;
	private ManageDB mdb = ManageDB.newInstance();
	
	public Connection conn() {
		try {
			Class.forName(mdb.getValue("jdbcDriver"));
		} catch (ClassNotFoundException e) {
			SimpleLogger.logException(e);
		}
		
		try {
			conn = DriverManager.getConnection(mdb.getValue("connectPath") + mdb.getValue("dbName") + "?user=" + mdb.getValue("user") + "&password=" + mdb.getValue("password"));
		} catch (SQLException e) {
			SimpleLogger.logException(e);
		}
		return conn;
	}
	
	public ResultSet query(final String sql) {
		try {
			conn();
			stmt = conn.createStatement();
		} catch (SQLException e) {
			SimpleLogger.logException(e);
		}
		
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			SimpleLogger.logException(e);
		}
		
		return rs;
	}
	
	public void update(String sql) {
		try {
		 conn();
			stmt = conn.createStatement();
		stmt.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	public void update(String sql, String[] args) {
		try {
			conn();
			pstmt = conn.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		int length = args.length;
		for(int i=0; i<length; i++) {
			try {
				pstmt.setString(i+1, args[i]);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void close() {
		if(rs != null) {
			try {
				rs.close();
				rs = null;
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				rs = null;
			}
		}
		
		if(stmt != null) {
			try {
				stmt.close();
				stmt = null;
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				stmt = null;
			}
		}
		
		if(pstmt != null) {
			try {
				pstmt.close();
				pstmt = null;
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				pstmt = null;
			}
		}
		
		if(rs != null) {
			try {
				rs.close();
				rs = null;
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				rs = null;
			}
		}
		
		
		
		
		
		
		
	}
	
}
